package com.siruier.boss.ad

import com.siruier.boss.api.core.globalLaunchUI
import com.siruier.boss.ui.utils.Logger
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay

object VideoPayTimeTimer {
    const val MAX_TIME = 5 * 60
    private var job: Job? = null
    private val TIMER = mutableMapOf<Any, VideoPayTimeTimeItem>()

    /**
     * 启动1秒执行一次定时器
     */
    fun startTimer() {
        job = globalLaunchUI({
            while (true) {
                delay(1000)
                TIMER.values.forEach(VideoPayTimeTimeItem::add)
            }
        })
    }

    fun destroyTimer() {
        job?.cancel()
        TIMER.clear()
    }

    fun registerTimer(key: Any, listener: VideoPayTimeTimeOutListener) {
        val item = TIMER[key]
        if (item == null) {
            TIMER[key] = VideoPayTimeTimeItem(listener)
        } else {
            item.stop()
        }
    }

    fun startTimer(key: Any) {
        TIMER[key]?.start()
    }

    fun stopTimer(key: Any) {
        TIMER[key]?.stop()
    }

    fun removeTimer(key: Any) {
        TIMER.remove(key)
    }

    fun startFirst(key: Any) {
        // 一个都没有启动的就启动一个
        val isNotStart = TIMER.values.all { !it.isStart }
        if (isNotStart) {
            Logger.e("没有启动的，启动一个")
            startTimer(key)
        }
    }
}

private class VideoPayTimeTimeItem(
    var listener: VideoPayTimeTimeOutListener?
) {

    private var current: Long = 0
    var isStart = false

    fun start() {
        isStart = true
    }

    fun stop() {
        isStart = false
        current = 0
    }

    fun add() {
        if (isStart) {
            current++
            if (current > VideoPayTimeTimer.MAX_TIME) {
                Logger.e("超时了===============")
                listener?.timeOut()
                stop()
            }
        }
    }
}

interface VideoPayTimeTimeOutListener {

    fun timeOut()
}